from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

import tensorflow as tf


#
# sess.run(tf.global_variables_initializer())
#
# y = tf.matmul(x, W) + b
#
# cross_entropy = tf.reduce_mean(
#     tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
#
# train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
#
# for _ in range(1000):
#     batch = mnist.train.next_batch(100)
#     train_step.run(feed_dict={x: batch[0], y_: batch[1]})
# correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
#
# accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#
# print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))


def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)


def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                          strides=[1, 2, 2, 1], padding='SAME')


def mnist_test(data):
    x = tf.placeholder(tf.float32, shape=[None, 784])
    y_ = tf.placeholder(tf.float32, shape=[None, 10])
    W = tf.Variable(tf.zeros([784, 10]))
    b = tf.Variable(tf.zeros([10]))

    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])

    x_image = tf.reshape(x, [-1, 28, 28, 1])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)

    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])

    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)

    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
    init_op = tf.initialize_all_variables()
    saver = tf.train.Saver()  # defaults to saving all variables
    with tf.Session() as sess:
        sess.run(init_op)
        saver.restore(sess, "d:/model.ckpt")  # 这里使用了之前保存的模型参数
        # print ("Model restored.")

        prediction = tf.argmax(y_conv, 1)
        pred_int = prediction.eval(feed_dict={x: [data], keep_prob: 1.0}, session=sess)
        print(h_conv2)

        print('recognize result:')
        print(pred_int[0])


from tkinter import *
import numpy as np

canvas_width = 280
canvas_height = 280
scale = 10

img_data = np.zeros((canvas_width, canvas_height))
img_small_data = np.zeros((int(canvas_width / scale), int(canvas_height / scale)))
main_canvas = None


def paint(event):
    if event.x >= canvas_width or event.y >= canvas_height:
        return
    # print("%d,%d" % (event.x, event.y))
    python_green = "#000000"
    img_data[event.y][event.x] = 1
    x1, y1 = (event.x - 1), (event.y - 1)
    x2, y2 = (event.x + 1), (event.y + 1)
    main_canvas.create_oval(x1, y1, x2, y2, fill=python_green)


def key_handle(event):
    if event.keycode == 13:
        w, h = img_data.shape
        for i in range(w):
            for j in range(h):
                x = int(i / scale)
                y = int(j / scale)
                # print("%d,%d" % (x, y))
                # print(int(img_data[i][i]), end='')
                img_small_data[x][y] = img_small_data[x][y] if img_small_data[x][y] >= img_data[i][j] else img_data[i][
                    j]
        w, h = img_small_data.shape
        for i in range(w):
            print('')
            for j in range(h):
                print(int(img_small_data[i][j]), end='')
                mnist_test(img_small_data.reshape(-1))


def tk_main():
    global main_canvas
    master = Tk()
    master.title("手写数字测试")
    master.geometry('%dx%d+500+200' % (canvas_width, canvas_height))
    master.resizable(0, 0)
    main_canvas = Canvas(master,
                         bg='white',
                         width=canvas_width,
                         height=canvas_height)
    main_canvas.pack(expand=YES, fill=BOTH)
    main_canvas.bind_all("<B1-Motion>", paint)
    main_canvas.bind_all("<KeyPress>", key_handle)
    # message = Label(master, text="Press and Drag the mouse to draw")
    # message.pack(side=BOTTOM)
    mainloop()

if __name__ == '__main__':
    ten